package Utils;

import domain.PDU.Tag.TagType;
import domain.PDU.VariableBindings;

import java.util.Arrays;
import java.util.HashMap;

/**
 * @Author: ylc
 * @Description:
 */
public class DecodingUtil {
    Util util = new Util();
    HashMap<Byte, String> codingTag = TagType.getCodingTag();

    /**
     * 获取当前下标所指向的标签值
     * @param snmp
     * @param index
     * @return
     */
    public String getValue(byte[] snmp,int index){
        String type = TagType.getCodingTag().get(snmp[index]);
        String value = null;
        switch (type){
            case TagType.BOOLEAN:
                value = getBooleanValue(snmp, index);
                break;
            case TagType.INTEGER:
                value = getInteger(snmp, index);
                break;
            case TagType.OCTET_STRING:
                value = getObjectString(snmp, index);
                break;
            case TagType.NULL:
                value = getNull();
                break;
            case TagType.OBJECT_IDENTIFIER:
                value = getOID(snmp, index);
                break;
            default:
                break;
        }
        return value;
    }

    /**
     * 获取BOOLEAN类型值
     * @param packet
     * @param index     标签所在的下标
     * @return
     */
    private String getBooleanValue(byte[] packet, int index) {
        byte flag = packet[index + 2];

        if(flag == 0x00){
            return "FALSE";
        }else{
            return "TRUE";
        }
    }

    /**
     * 获取INTEGER类型值值
     * @param packet
     * @param index 整型标签所在的下标
     * @return  整型值
     */
    private String getInteger(byte[] packet, int index) {
        // 获取Integer的长度
        int len = packet[index + 1];
        byte[] value = Arrays.copyOfRange(packet,index+2,index+2+len);

        return "" + util.bytesToInt(value);
    }

    /**
     * 获取OBJECT STRING类型值
     * @param packet
     * @param index
     * @return
     */
    private String getObjectString(byte[] packet, int index) {
        // 获取ObjectString的长度
        int len = packet[index + 1];
        byte[] value = Arrays.copyOfRange(packet,index+2,index+2+len);

        return "" + util.bytesToSring(value);
    }

    /**
     * 获取NULL类型值
     * @return
     */
    private String getNull() {
        return "NULL";
    }

    /**
     * 获取OBJECT IDENTIFIER类型值
     * @param packet
     * @param index
     * @return
     */
    private String getOID(byte[] packet, int index) {
        int len = packet[index + 1];
        byte[] value = Arrays.copyOfRange(packet,index+2,index+2+len);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < value.length - 1; i++) {
            if(value[i] == 0x2B){
                sb.append("1.3.");
                continue;
            }
            sb.append(value[i]);
            sb.append(".");
        }
        sb.append(value[len - 1]);
        return sb.toString();
    }
}
